package wish.filters;

import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;

import wish.model.Record;


public class HTMLTagStructureFilter implements Filter{

	private int minimumNumberOfTags;

	public HTMLTagStructureFilter(int minimumNumberOfTags){
		this.minimumNumberOfTags = minimumNumberOfTags;
	}
	
	@Override
	public Record filter(Record region) {
		
		SimpleNodeIterator listToFilter = region.getNodeList().elements();
		
		NodeList nodeList = new NodeList();
				
		while (listToFilter.hasMoreNodes()){
			
			Node node = listToFilter.nextNode();
	
			if (hasMorethanHTMLTags(node,minimumNumberOfTags)){
				
				nodeList.add(node);
				
			}
			
		}
		
		if (nodeList.size() > 0){
			
			return new Record(region.getFather(),region.getLevel(), region.getTag(), nodeList, nodeList.size());
			
		}
		
		return null;
		
	}

	private boolean hasMorethanHTMLTags(Node node, int minimumNumberOfTags) {
		
		int numberOfTags = getNumberOfTags(node,minimumNumberOfTags);		
		
		return numberOfTags >= minimumNumberOfTags;
			
	}

	private int getNumberOfTags(Node node, int minimumNumberOfTags) {

		if (node.getChildren() == null){
			if (node instanceof TagNode)
				return 1;
			return 0;
			
		}
		
		SimpleNodeIterator iterator = node.getChildren().elements();
		
		int numberOfTags = 0;
		
		if (node instanceof TagNode)
			numberOfTags = 1; //Head
		
		while (iterator.hasMoreNodes()){
			
			numberOfTags += getNumberOfTags(iterator.nextNode(),minimumNumberOfTags);
			
			if (numberOfTags >= minimumNumberOfTags){
				return numberOfTags;
			}
			
		}
		
		return numberOfTags;
	}

		
}
